<template>
	<view class="pitfall-list-page">
		<!-- 顶部固定区域 -->
		<view class="sticky-header" id="sticky-header">
			<view class="custom-tabs-container">
				<view
					v-for="(tab, index) in subTabList"
					:key="index"
					:class="['custom-tab-item', { 'active': currentSubTab === index }]"
					@click="handleSubTabChange(index)"
				>
					<image 
						v-if="tab.icon"
						class="custom-tab-icon"
						:src="tab.icon" 
						mode="aspectFit"
					></image>
					<text class="custom-tab-text">{{ tab.name }}</text>
				</view>
			</view>
		</view>

		<!-- 主内容滚动区 -->
		<scroll-view 
			scroll-y 
			class="content-scroll-view" 
			:style="{ height: `calc(100vh - ${stickyHeaderHeight}px)`, paddingTop: stickyHeaderHeight + 'px' }"
			@scrolltolower="onScrollToLower"
			refresher-enabled
			:refresher-triggered="isRefresherTriggered"
			@refresherrefresh="handleRefresh"
		>
			<!-- 坑言坑语瀑布流 -->
			<view class="pit-talk-section">
				<view class="section-header">
					<text class="title">坑言坑语</text>
					<text class="subtitle">唠唠踩坑那些破事儿</text>
				</view>
				<view class="post-waterfall">
					<view class="waterfall-container">
						<view class="waterfall-column">
							<view class="post-item" v-for="item in leftList" :key="item.id" @click="navigateToPostDetail(item)">
								<image class="post-image" :src="item.image" mode="widthFix"></image>
								<view class="post-info-card">
									<text class="post-title">{{ item.content }}</text>
									<view class="author-info">
										<view class="author-left">
											<u-avatar :src="item.author.avatar" size="30"></u-avatar>
											<text class="author-name">{{ item.author.name }}</text>
										</view>
										<view class="likes-info">
											<u-icon name="heart" color="#666" size="14"></u-icon>
											<text class="like-count">{{ item.likeCount | formatLikes }}</text>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view class="waterfall-column">
							<view class="post-item" v-for="item in rightList" :key="item.id" @click="navigateToPostDetail(item)">
								<image class="post-image" :src="item.image" mode="widthFix"></image>
								<view class="post-info-card">
									<text class="post-title">{{ item.content }}</text>
									<view class="author-info">
										<view class="author-left">
											<u-avatar :src="item.author.avatar" size="30"></u-avatar>
											<text class="author-name">{{ item.author.name }}</text>
										</view>
										<view class="likes-info">
											<u-icon name="heart" color="#666" size="14"></u-icon>
											<text class="like-count">{{ item.likeCount | formatLikes }}</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<u-loadmore :status="loadStatus" />
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { getPosts } from '@/request/api.js';
import config from '@/config/index.js';

const PAGE_SIZE = 10;

export default {
	data() {
		return {
			stickyHeaderHeight: 0,
			currentSubTab: 0,
			subTabList: [ // 和 pit-avoidance.vue 保持一致
				{ name: '综合', queryType: 0, icon: null },
				{ name: '美食', queryType: 1 ,icon: '/static/pit-avoidance/icon_food.png' }, 
				{ name: '景点', queryType: 2 ,icon: '/static/pit-avoidance/icon_jd.png' }, 
				{ name: '出行', queryType: 3 ,icon: '/static/pit-avoidance/icon_jt.png' }, 
				{ name: '体验', queryType: 4 ,icon: '/static/pit-avoidance/icon_rw.png' }
			],
			leftList: [],
			rightList: [],
			page: 1,
			loadStatus: 'loadmore',
			isLoading: false,
			hasMore: true,
			isRefresherTriggered: false
		};
	},
	filters: {
		formatLikes(val) {
			if (val >= 10000) return (val / 10000).toFixed(1) + 'w';
			if (val >= 1000) return (val / 1000).toFixed(1) + 'k';
			return val;
		}
	},
	onLoad(options) {
		if (options.currentTab) {
			this.currentSubTab = parseInt(options.currentTab, 10);
		}
		this.loadPitPosts(true); // 加载初始数据
	},
	onReady() {
		// 动态计算顶部固定区域的高度
		const query = uni.createSelectorQuery().in(this);
		query.select('#sticky-header').boundingClientRect(data => {
			if (data) {
				this.stickyHeaderHeight = data.height;
			}
		}).exec();
	},
	methods: {
		handleSubTabChange(index) {
			if (this.currentSubTab === index) return;
			this.currentSubTab = index;
			this.loadPitPosts(true); // 切换Tab时，刷新数据
		},
		handleRefresh() {
			this.isRefresherTriggered = true;
			this.loadPitPosts(true);
		},
		onScrollToLower() {
			this.loadPitPosts(false);
		},
		async loadPitPosts(isRefresh = false) {
			if (this.isLoading || (!this.hasMore && !isRefresh)) return;

			this.isLoading = true;
			
			if (isRefresh) {
				this.page = 1;
				this.leftList = [];
				this.rightList = [];
				this.hasMore = true;
				this.loadStatus = 'loading';
			} else {
				this.loadStatus = 'loading';
			}
			
			const currentQueryType = this.subTabList[this.currentSubTab].queryType;
			const params = {
				userId: this.$store.state.userInfo?.userId,
				queryType: currentQueryType,
				pageNum: this.page,
				pageSize: PAGE_SIZE
			};

			try {
				const res = await getPosts(params);
				if (res.data?.code === 200) {
					const formattedPosts = (res.data.rows || []).map(this.formatApiData);
					this.distributePostsToColumns(formattedPosts);
					
					this.hasMore = formattedPosts.length === PAGE_SIZE;
					if (this.hasMore) {
						this.page++;
					}
				} else {
					console.error(`加载瀑布流失败:`, res.data.msg);
				}
			} catch (error) {
				console.error(`请求瀑布流失败:`, error);
			} finally {
				this.loadStatus = this.hasMore ? 'loadmore' : 'nomore';
				this.isLoading = false;
				if (isRefresh) {
					this.isRefresherTriggered = false;
				}
			}
		},
		distributePostsToColumns(newPosts) {
			newPosts.forEach(post => {
				if (this.leftList.length <= this.rightList.length) {
					this.leftList.push(post);
				} else {
					this.rightList.push(post);
				}
			});
		},
		formatApiData(item) {
			const coverImage = (item.files && item.files.length > 0)
				? (item.files[0].fileUrl.startsWith('http') ? item.files[0].fileUrl : config.cdnURL + item.files[0].fileUrl)
				: 'https://picsum.photos/seed/default/400/300';
			const authorAvatar = item.avatar
				? (item.avatar.startsWith('http') ? item.avatar : config.cdnURL + item.avatar)
				: '/static/demo/avatar_default.png';
			return { id: item.id, image: coverImage, title: item.content, author: { avatar: authorAvatar, name: item.nickName || '匿名用户' }, isLiked: item.isLiked, likeCount: item.likeCount, ...item };
		},
		navigateToSearch() { uni.navigateTo({ url: '/pages_sub/common/search-suggestions/search-suggestions' }); },
		navigateToPostDetail(item) {
			uni.navigateTo({
				url: `/pages_sub/index/rich-post-detail/rich-post-detail`,
				success: (res) => res.eventChannel.emit('acceptDataFromOpenerPage', { item: item })
			});
		},
	}
};
</script>

<style lang="scss" scoped>
.pitfall-list-page {
	position: relative; /* 必须设置，为 ::before 伪元素提供定位上下文 */
	overflow: hidden;   /* 防止模糊效果的边缘溢出，保持页面整洁 */
	display: flex;
	flex-direction: column;
	height: 100vh;
	
	/* 基础的颜色渐变背景 */
	background: linear-gradient(to bottom, #FDF6EC, #ffffff);
}

/* 2. 创建磨砂质感覆盖层 */
.pitfall-list-page::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 0; /* 将伪元素置于内容之下 (z-index: 1) */
	
	/* 关键：实现磨砂效果 */
	/* blur() 的值可以调整，数值越大越模糊。20px 是一个比较柔和的效果。 */
	backdrop-filter: blur(20px);
	-webkit-backdrop-filter: blur(20px); /* 兼容 Safari */
	
	/* 可选：再叠加一层非常淡的白色，可以增强磨砂感和亮度 */
	background-color: rgba(255, 255, 255, 0.1); 
}

.sticky-header {
	position: fixed;
	// top: 0;
	left: 0;
	right: 0;
	z-index: 99;
	background-color: rgba(255, 255, 255, 0.6) !important; /* 吸顶时给一个半透明背景，更有层次感 */
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	
	.custom-tabs-container {
		padding-left: 30rpx;
		padding-right: 30rpx;
	}
	
    // 复用 pit-avoidance.vue 的样式
	
	.custom-tabs-container {
		display: flex; align-items: center; justify-content: space-between; padding: 10rpx 20rpx; border-bottom: 1rpx solid #f8f8f8;
	}

	.custom-tab-item {
		display: flex; align-items: center; justify-content: center; padding: 10rpx 0;
		.custom-tab-icon { width: 40rpx; height: 40rpx; margin-right: 8rpx; }
		.custom-tab-text { font-size: 30rpx; color: #666; transition: all 0.2s; }
		&.active .custom-tab-text { font-weight: bold; color: #000; }
	}
}

.content-scroll-view {
	position: relative; /* 确保 z-index 生效 */
	z-index: 1;         /* 高于 ::before 伪元素的 z-index: 0 */
	background-color: transparent !important; /* 必须是透明的，才能透出下方的磨砂背景 */
}

.pit-talk-section {
	padding: 30rpx;
	flex: 1;
	background-color: transparent;
	
	.section-header {
		display: flex; align-items: flex-end; margin-bottom: 20rpx;
		.title { font-size: 34rpx; font-weight: bold; margin-right: 16rpx; position: relative;
			&::after { content: ''; position: absolute; bottom: -4rpx; left: 0; width: 100%; height: 12rpx; background-color: #FBD13E; z-index: -1; }
		}
		.subtitle { font-size: 24rpx; color: #999; }
	}
}

.post-waterfall { padding: 0; }
.waterfall-container { display: flex; justify-content: space-between;
	.waterfall-column { width: 48.5%; display: flex; flex-direction: column; }
}
.post-item {
	background-color: #fff; border-radius: 12rpx; overflow: hidden; margin-bottom: 20rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	.post-image { width: 100%; display: block; }
	.post-info-card { padding: 15rpx; }
	.post-title { font-size: 26rpx; color: #333; line-height: 1.4; margin-bottom: 10rpx; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; }
}
.author-info {
	display: flex; justify-content: space-between; align-items: center; margin-top: 10rpx;
	.author-left {
		display: flex; align-items: center;
		.author-name { margin-left: 10rpx; font-size: 22rpx; color: #666; max-width: 150rpx; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
	}
	.likes-info {
		display: flex; align-items: center;
		.like-count { margin-left: 5rpx; font-size: 22rpx; color: #666; }
	}
}
</style>